
package de.justphil.tcg.tcgandroidclient.content.view;

import android.database.ContentObserver;
import android.os.Handler;
import de.justphil.tcg.tcgandroidclient.content.TCGContentAdapter;
import de.justphil.tcg.tcgandroidclient.util.StringTools;
import de.justphil.tcg.tcgandroidclient.util.TCGLog;

/**
 * @author Martin Immutable
 * 
 * 
 */
public class ViewDeck extends ViewData {
	
	private final TCGContentAdapter contentAdapter;
	private final long deckId;
	/* */
	private ViewCard[] cards;
	// private ContentObserver cardIdsObserver;
	/* */
	private String name;
	
	// private ContentObserver nameObserver;
	public ViewDeck(TCGContentAdapter contentAdapter, ContentObserver obs, long deckId) {
	
		super(obs);
		this.deckId = deckId;
		this.contentAdapter = contentAdapter;
	}
	
	public ViewDeck(TCGContentAdapter contentAdapter, ContentObserver obs, long deckId, String name) {
	
		this(contentAdapter, obs, deckId);
		this.name = name;
		TCGLog.d(new Object[] {
				"Created deck ", getDeckId(),"." });
	}
	
	@Override
	public String toString() {
	
		return StringTools.getString(new Object[] {
				getName(), " (", getDeckId(), ")" });
	}
	
	public long getDeckId() {
	
		return deckId;
	}
	
	
	public ViewCard[] getCards() {
	
		if (cards == null) {
			setCards(contentAdapter.readDeckToCards(getDeckId(), getContentObserver()));
		}
		// resetNotification();
		return cards;
	}
	
	public String getName() {
	
		if (name == null) {
			setName(contentAdapter.readDeck(getDeckId(), getContentObserver()));
		}
		// resetNotification();
		return name;
	}
	
	private void setName(String name) {
	
		if (name == null || "".equals(name) || "NULL".equals(name)) {
			name = "unknown";
		}
		
		this.name = name;
		// onChange();
	}
	
	private void setCards(long[] cardIds) {
	
		this.cards = new ViewCard[cardIds.length];
		for (int i = 0; i < cardIds.length; i++) {
			cards[i] = new ViewCard(contentAdapter, getContentObserver(), cardIds[i]);
		}
		// onChange();
	}
	// private ContentObserver getNameObserver() {
	//
	// if (nameObserver == null) {
	// nameObserver = new ContentObserver(new Handler()) {
	//
	// @Override
	// public void onChange(boolean selfChange) {
	//
	// setName(contentAdapter.readDeck(getDeckId(), null));
	// }
	// };
	// }
	// return nameObserver;
	// }
	//
	// private ContentObserver getCardIdsObserver() {
	//
	// if (cardIdsObserver == null) {
	// cardIdsObserver = new ContentObserver(new Handler()) {
	//
	// @Override
	// public void onChange(boolean selfChange) {
	//
	// setCards(contentAdapter.readDeckToCards(getDeckId(), null));
	// }
	// };
	// }
	// return cardIdsObserver;
	// }
}
